package com.horse.three60;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.horse.ui.LearningView;
import com.horse.utils.Constants;
import com.horse.utils.DownloadCompletionListener;
import com.horse.utils.Downloader;
import com.horse.utils.DownloadingItem;
import com.horse.utils.ImageName;
import com.horse.utils.NoRepeatRandom;
import com.horse.utils.Utils;
import com.inapp.util.BillingService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class LearningBeforeActivity extends Activity implements OnClickListener {

	private Button backButton;
	private Button startButton;
	private ImageView timeView;
	private ImageView normalView;

	private boolean isTimedClicked;

	private JSONObject jo;
	private String fileNames[];

	public static LearningView learnView;
	private int level;

	private int fileIndex = -1;

	private static final String FOLDER_NAME = "Horse 360";
	public static final File ROOT_DIR = new File(Environment
			.getExternalStorageDirectory().getAbsolutePath(), FOLDER_NAME);

	private int imageIndex = 0;

	private String BASE_URL = "";

	private boolean isLevelUnlocked[] = new boolean[20];
	private boolean isFilesDownloaded[] = new boolean[20];

	private boolean isTimer;

	private ImageView quizView;

	private String imageFileName[];

	private int unlockedLevels[];

	private String IMAGE_DIRECTORY;

	private int nextLevel;

	private int learnScore[] = new int[21];
	private int percent[] = new int[21];

	private boolean musclesDownloaded;
	private boolean hoovesDownloaded;
	private boolean tendonsDownloaded;
	private boolean headDownloaded;
	private boolean organsDownloaded;

	private SharedPreferences sharedPreferences;
	private final OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if (BillingService.KEY_IN_APP_PURCHASED_ITEM_CHANGED_TIME
						.equals(key)) {
					runOnUiThread(new Runnable() {
						public void run() {
							manageLockedLevels();
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onDestroy() {
		try {
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {

			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_before_learning);

			try {
				sharedPreferences = PreferenceManager
						.getDefaultSharedPreferences(this);
				sharedPreferences
						.registerOnSharedPreferenceChangeListener(ospcl);
			} catch (Exception e) {
				e.printStackTrace();
			}

			backButton = (Button) findViewById(R.id.backButton);
			backButton.setOnClickListener(this);

			startButton = (Button) findViewById(R.id.startButton);
			startButton.setOnClickListener(this);

			quizView = (ImageView) findViewById(R.id.quizView);

			timeView = (ImageView) findViewById(R.id.timedView);
			timeView.setOnClickListener(this);

			normalView = (ImageView) findViewById(R.id.normalView);
			normalView.setOnClickListener(this);

			learnView = (LearningView) findViewById(R.id.learnView);

			nextLevel = getIntent().getIntExtra(Constants.KEY_NEXT_LEVEL, 0);
			if (nextLevel != 0) {
				String message = "";
				String title = "";
				switch (nextLevel) {
				case 3:
				case 4:
					title = "Muscle Layers need to be purchased";
					message = "Select a Muscle Level and press start";
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					title = "Hoof Layers need to be purchased";
					message = "Select a Hoof Level and press start";
					break;
				case 9:
				case 10:
				case 11:
				case 12:
					title = "Deep Muscle Layers need to be purchased";
					message = "Select a Deep Muscle Level and press start";
					break;

				case 13:
				case 14:
				case 15:
					title = "Head Layers need to be purchased";
					message = "Select a Head Level and press start";
					break;
				case 16:
				case 17:
				case 18:
				case 19:
					title = "Organ and Conformation Layers need to be purchased";
					message = "Select a Organ and Conformation Level and press start";
					break;
				default:
					break;
				}
				Utils.showAlertMessage(LearningBeforeActivity.this, title,
						message);
			}

			manageLockedLevels();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void manageLockedLevels() {
		try {

			isLevelUnlocked = Utils.getUnlockedLevels(sharedPreferences);
			for(int i=0;i<isLevelUnlocked.length;i++){
				Log.i("DREG", "INDEX="+i+",VAL="+isLevelUnlocked[i]);
			}
			
			isFilesDownloaded = Utils.getFilesDownloaded();
			for (int i = 0; i < 20; i++) {
				
				learnScore[i] = Utils.getLevelHighestScore(
						LearningBeforeActivity.this,
						Constants.KEY_LEARNING_SCORE + i);
				percent[i] = Utils.getLevelHighestScore(
						LearningBeforeActivity.this,
						Constants.KEY_LEARNING_PERCENTAGE + i);
				Log.i("DREG", "Learn Score =" + learnScore[i]);
			}
			learnView.setLockedLevel(isLevelUnlocked);
			learnView.setScore(learnScore, percent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent backIntent = new Intent(LearningBeforeActivity.this,
					HomeScreenActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.timedView:
			if (!isTimer) {
				timeView.setImageResource(R.drawable.timed_selected);
				normalView.setImageResource(R.drawable.normal_unselected);
				isTimer = true;
			}
			break;
		case R.id.normalView:
			if (isTimer) {
				timeView.setImageResource(R.drawable.timed_unselected);
				normalView.setImageResource(R.drawable.normal_selected);
				isTimer = false;
			}
			break;
		case R.id.startButton:
			level = LearningView.getSelectedIndex();
			levelWiseOperation(level);
			break;

		case R.id.backButton:
			Intent backIntent = new Intent(LearningBeforeActivity.this,
					HomeScreenActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			break;

		default:
			break;
		}

	}

	private void levelWiseOperation(final int level) {
		try {
			List<DownloadingItem> downloadingItems = new ArrayList<DownloadingItem>();
			switch (level) {
			case 0:
			case 1:
			case 2:
				nagivateLearning(level);
				break;

			case 3:
			case 4:
				if (!isLevelUnlocked[level]) {
					if (Utils.isDeviceOnline(this)) {
						goToStore("Surficial muscle layers needs to be purchased");
					} else {
						Toast.makeText(this,
								"\t\tOpps ! !\nNo internet connection",
								Toast.LENGTH_SHORT).show();
					}
				} else if(isFilesDownloaded[level]){
					nagivateLearning(level);
				} else{
					if (Utils.isDeviceOnline(this)) {
						DownloadingItem di = new DownloadingItem();	
						di.setACHIEVEMENT_ID(Constants.MUSCLE_THERAPIST_ACHIEVEMENT_ID);
						di.setBASE_URL(Constants.MUSCLES_STANDARD_URL);
						di.setIMAGE_DIRECTORY(Constants.MUSLES_DIRECTORY);
						di.setImageFileName(ImageName.MUSCLES_IMAGES);
						downloadingItems.add(di);
						Utils.downloadFiles(LearningBeforeActivity.this,downloadingItems,new DownloadCompletionListener() {
							
							@Override
							public void onDownloadError(Exception exception) {
								Utils.showAlertMessage(LearningBeforeActivity.this, null, exception.getMessage());
							}
							
							@Override
							public void onCompleteDownloading() {
								isFilesDownloaded = Utils.getFilesDownloaded();
								nagivateLearning(level);
							}
						});
					}else{
						Utils.showAlertMessage(LearningBeforeActivity.this, null, "Please go online to download required files.");
					}
				}
				break;
			case 5:
			case 6:
			case 7:
			case 8:
				if (!isLevelUnlocked[level]) {
					if (Utils.isDeviceOnline(this)) {
						goToStore("Hoof layers needs to be purchased");
					} else {
						Toast.makeText(this,
								"\t\tOpps ! !\nNo internet connection",
								Toast.LENGTH_SHORT).show();
					}
				} else if(isFilesDownloaded[level]){
					nagivateLearning(level);
				} else{
					if (Utils.isDeviceOnline(this)) {
						DownloadingItem di = new DownloadingItem();
						di.setACHIEVEMENT_ID(Constants.HORSE_DENTIST_ACHIEVEMENT_ID);	
						di.setBASE_URL(Constants.HOOVES_RETINAL_URL);
						di.setIMAGE_DIRECTORY(Constants.HOOFS_DIRECTORY);
						di.setImageFileName(ImageName.HOOFS_IMAGES);
						downloadingItems.add(di);
						Utils.downloadFiles(LearningBeforeActivity.this,downloadingItems,new DownloadCompletionListener() {
							
							@Override
							public void onDownloadError(Exception exception) {
								Utils.showAlertMessage(LearningBeforeActivity.this, null, exception.getMessage());
							}
							
							@Override
							public void onCompleteDownloading() {
								isFilesDownloaded = Utils.getFilesDownloaded();
								nagivateLearning(level);
							}
						});
					}else{
						Utils.showAlertMessage(LearningBeforeActivity.this, null, "Please go online to download required files.");
					}
				}
				break;
			case 9:
			case 10:
			case 11:
			case 12:
				if (!isLevelUnlocked[level]) {
					if (Utils.isDeviceOnline(this)) {
						goToStore("Deep Muscle layers needs to be purchased");
					} else {
						Toast.makeText(this,
								"\t\tOpps ! !\nNo internet connection",
								Toast.LENGTH_SHORT).show();
					}

				} else if(isFilesDownloaded[level]){
					nagivateLearning(level);
				} else{
					if (Utils.isDeviceOnline(this)) {
						DownloadingItem di = new DownloadingItem();
						di.setACHIEVEMENT_ID(Constants.PRO_RIDER_WORLD_CHAMPION_ACHIEVEMENT_ID);
						di.setBASE_URL(Constants.TENDONS_STANDARD_URL);
						di.setIMAGE_DIRECTORY(Constants.DEEP_MUSCLES_DIRECTORY);
						di.setImageFileName(ImageName.TENDON_IMAGES);
						downloadingItems.add(di);
						Utils.downloadFiles(LearningBeforeActivity.this,downloadingItems,new DownloadCompletionListener() {
							
							@Override
							public void onDownloadError(Exception exception) {
								Utils.showAlertMessage(LearningBeforeActivity.this, null, exception.getMessage());
							}
							
							@Override
							public void onCompleteDownloading() {
								isFilesDownloaded = Utils.getFilesDownloaded();
								nagivateLearning(level);
							}
						});
					}else{
						Utils.showAlertMessage(LearningBeforeActivity.this, null, "Please go online to download required files.");
					}
				}
				break;
			case 13:
			case 14:
			case 15:
				if (!isLevelUnlocked[level]) {
					if (Utils.isDeviceOnline(this)) {

						goToStore("Head layers needs to be purchased");

					} else {
						Toast.makeText(this,
								"\t\tOpps ! !\nNo internet connection",
								Toast.LENGTH_SHORT).show();
					}
				} else if(isFilesDownloaded[level]){
					nagivateLearning(level);
				} else{
					if (Utils.isDeviceOnline(this)) {
						DownloadingItem di = new DownloadingItem();
						di.setACHIEVEMENT_ID(Constants.CHIROPRACTOR_ACHIEVEMENT_ID);
						di.setBASE_URL(Constants.HEAD_STANDARD_URL);
						di.setIMAGE_DIRECTORY(Constants.HEAD_DIRECTORY);
						di.setImageFileName(ImageName.HEAD_IMAGES);
						downloadingItems.add(di);
						Utils.downloadFiles(LearningBeforeActivity.this,downloadingItems,new DownloadCompletionListener() {
							
							@Override
							public void onDownloadError(Exception exception) {
								Utils.showAlertMessage(LearningBeforeActivity.this, null, exception.getMessage());
							}
							
							@Override
							public void onCompleteDownloading() {
								isFilesDownloaded = Utils.getFilesDownloaded();
								nagivateLearning(level);
							}
						});
					}else{
						Utils.showAlertMessage(LearningBeforeActivity.this, null, "Please go online to download required files.");
					}
				}
				break;
			case 16:
			case 17:
			case 18:
			case 19:
				if (!isLevelUnlocked[level]) {
					if (Utils.isDeviceOnline(this)) {
						Log.i("DREG", "Level = " + level);
						goToStore("Organ and Conformation needs to be purchased");
					} else {
						Toast.makeText(this,
								"\t\tOpps ! !\nNo internet connection",
								Toast.LENGTH_SHORT).show();
					}
				} else if(isFilesDownloaded[level]){
					nagivateLearning(level);
				} else{
					if (Utils.isDeviceOnline(this)) {
						DownloadingItem di = new DownloadingItem();
						di.setACHIEVEMENT_ID(Constants.FARRIER_ACHIEVEMENT_ID);
						di.setBASE_URL(Constants.ORGANS_STANDARD_URL);
						di.setIMAGE_DIRECTORY(Constants.ORGANS_DIRECTORY);
						di.setImageFileName(ImageName.ORGANS_IMAGES);
						downloadingItems.add(di);
						Utils.downloadFiles(LearningBeforeActivity.this,downloadingItems,new DownloadCompletionListener() {
							
							@Override
							public void onDownloadError(Exception exception) {
								Utils.showAlertMessage(LearningBeforeActivity.this, null, exception.getMessage());
							}
							
							@Override
							public void onCompleteDownloading() {
								isFilesDownloaded = Utils.getFilesDownloaded();
								nagivateLearning(level);
							}
						});
					}else{
						Utils.showAlertMessage(LearningBeforeActivity.this, null, "Please go online to download required files.");
					}
				}
				break;
			case 20:
				nagivateLearning(level);
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	String jsonFileName;

	private void nagivateLearning(int level) {
		Intent intent = new Intent(LearningBeforeActivity.this,
				LearningQuizeActivity.class);
		Log.i("DREG", "is Normal=" + isTimer);
		intent.putExtra(Constants.KEY_IS_TIMER, isTimer);
		intent.putExtra(Constants.KEY_LEVEL, level);
		startActivity(intent);
	}

	private String getJString() {
		try {

			switch (level) {
			case 0:
				jsonFileName = "Level 1-Quiz 1.json";
				break;
			case 1:
				jsonFileName = "Level 2-Quiz 1.json";
				break;
			case 2:
				jsonFileName = "Level 3-Quiz 1.json";
				break;
			case 3:
				jsonFileName = "Level 4-Quiz 1.json";
				IMAGE_DIRECTORY = Constants.MUSLES_DIRECTORY;
				imageFileName = ImageName.MUSCLES_IMAGES;
				BASE_URL = Constants.MUSCLES_STANDARD_URL;
				break;

			case 4:
				jsonFileName = "Level 5-Quiz 1.json";
				IMAGE_DIRECTORY = Constants.MUSLES_DIRECTORY;
				imageFileName = ImageName.MUSCLES_IMAGES;
				BASE_URL = Constants.MUSCLES_STANDARD_URL;
				break;
			case 5:
				jsonFileName = "Level Hoof 1-Quiz 1.json";
				IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
				imageFileName = ImageName.HOOFS_IMAGES;
				BASE_URL = Constants.HOOVES_RETINAL_URL;
				break;
			case 6:
				jsonFileName = "Level Hoof 2-Quiz 1.json";
				IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
				imageFileName = ImageName.HOOFS_IMAGES;
				BASE_URL = Constants.HOOVES_RETINAL_URL;
				break;
			case 7:
				jsonFileName = "Level Hoof 3-Quiz 1.json";
				IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
				imageFileName = ImageName.HOOFS_IMAGES;
				BASE_URL = Constants.HOOVES_RETINAL_URL;
				break;
			case 8:
				jsonFileName = "Level Hoof 4-Quiz 1.json";
				IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
				imageFileName = ImageName.HOOFS_IMAGES;
				BASE_URL = Constants.HOOVES_RETINAL_URL;
				break;
			case 9:
				BASE_URL = Constants.TENDONS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
				imageFileName = ImageName.TENDON_IMAGES;
				jsonFileName = "Level Tendon 1-Quiz 1.json";
				break;
			case 10:
				BASE_URL = Constants.TENDONS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
				imageFileName = ImageName.TENDON_IMAGES;
				jsonFileName = "Level Tendon 2-Quiz 1.json";
				break;
			case 11:
				BASE_URL = Constants.TENDONS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
				imageFileName = ImageName.TENDON_IMAGES;
				jsonFileName = "Level Joints 1-Quiz 1.json";
				break;
			case 12:
				BASE_URL = Constants.TENDONS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
				imageFileName = ImageName.TENDON_IMAGES;
				jsonFileName = "Level Ligaments 1-Quiz 1.json";
				break;
			case 13:
				BASE_URL = Constants.HEAD_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
				imageFileName = ImageName.HEAD_IMAGES;
				jsonFileName = "Level Head Muscle 1-Quiz 1.json";
				break;
			case 14:
				BASE_URL = Constants.HEAD_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
				imageFileName = ImageName.HEAD_IMAGES;
				jsonFileName = "Level Head Bone 1-Quiz 1.json";
				break;
			case 15:
				BASE_URL = Constants.HEAD_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
				imageFileName = ImageName.HEAD_IMAGES;
				jsonFileName = "Level Teeth 1-Quiz 1.json";
				break;
			case 16:
				BASE_URL = Constants.ORGANS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
				imageFileName = ImageName.ORGANS_IMAGES;
				jsonFileName = "Level Organs 1-Quiz 1.json";
				break;
			case 17:
				BASE_URL = Constants.ORGANS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
				imageFileName = ImageName.ORGANS_IMAGES;
				jsonFileName = "Level Organs 2-Quiz 1.json";
				break;
			case 18:
				BASE_URL = Constants.ORGANS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
				imageFileName = ImageName.ORGANS_IMAGES;
				jsonFileName = "Level Conformation 1-Quiz 1.json";
				break;
			case 19:
				BASE_URL = Constants.ORGANS_STANDARD_URL;
				IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
				imageFileName = ImageName.ORGANS_IMAGES;
				jsonFileName = "Level Conformation 2-Quiz 1.json";
				break;
			case 20:
				jsonFileName = "Level 6-Quiz 1.json";
				break;
			default:
				jsonFileName = "Level 1-Quiz 1.json";
				break;
			}

			jo = new JSONObject(new String(
					Utils.getFileData(this, jsonFileName)));
			return jo.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	

	private String items[] = { "\t\tGo to Store", "\t\tCancel" };

	private void goToStore(String title) {
		new AlertDialog.Builder(this).setTitle(title)
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface alert, int position) {
						switch (position) {
						case 0:
							alert.cancel();
							goTopurchaseScreen();
							break;
						case 1:
							alert.cancel();
							break;

						}
					}
				}).show();
	}

	
	private void goTopurchaseScreen() {
		Intent intent = new Intent(LearningBeforeActivity.this,
				PurchaseActivity.class);
		intent.putExtra(Constants.KEY_QUIZ,
				getIntent().getIntExtra(Constants.KEY_QUIZ, 0));
		intent.putExtra(Constants.KEY_LEVEL, level);
		startActivity(intent);
	}

}
